import {
  DeleteOutlined,
  DownloadOutlined,
  EditOutlined,
  SearchOutlined,
  SyncOutlined,
} from "@ant-design/icons";
import {
  Button,
  Card,
  Drawer,
  Form,
  Input,
  message,
  Popconfirm,
  Table,
  Tag,
} from "antd";
import React, { useEffect, useState } from "react";
import "../../DepartmentManage/views/style.css";
import TableToolbar from "../../../components/TableSetting/TableToolbar";
import AddSchool from "./AddSchool";
import { Store } from "rc-field-form/lib/interface";
import { fetchRequest } from "../../../utils/Request";
import { url } from "../../../utils/url";
import { useDispatch, useSelector } from "react-redux";
import { useRequest } from "@umijs/hooks";
import ModifySchool from "./ModifySchool";
import schoolType from "../schoolType";
import exportExcel from "@/utils/exportExcel";

interface RequestParams {
  collegeName: string | undefined;
  contact: string | undefined;
  contactPhone: string | undefined;
  begin: number;
  len: number;
}

interface ModifyInfo {
  content: any;
  visible: boolean;
}

interface DeleteParams {
  collegeID: string;
}

export default function SchoolManageTable() {
  const [modify, setmodify] = useState<ModifyInfo>({
    content: null,
    visible: false,
  });

  const columns = [
    { title: "学校名称", dataIndex: "collegeName", key: "collegeName" },
    { title: "学校地址", dataIndex: "addrDesc", key: "addrDesc" },
    { title: "学校管理人", dataIndex: "contact", key: "contact" },
    {
      title: "学校管理人手机号",
      dataIndex: "contactPhone",
      key: "contactPhone",
    },
    { title: "创建时间", dataIndex: "createDate", key: "createDate" },
    /*注释是否人脸必须*/
    // {
    //     title: "是否人脸必须", dataIndex: "isFaceNecessary", key: "isFaceNecessary",
    //     render: (record: string) => record === "1" ?
    //         <Tag color="green">人脸必须</Tag> : <Tag color="red">人脸非必须</Tag>
    // },
    // {
    //     title: "是否物业", dataIndex: "isPropManageCom", key: "isPropManageCom",
    //     render: (record: string) => record === "1" ?
    //         <Tag color="green">是</Tag> : <Tag color="red">否</Tag>
    // },
    {
      title: "操作",
      render: (record: any) => {
        return (
          <small onClick={(e) => e.stopPropagation()}>
            <Tag
              className="tags-hover"
              color="#108ee9"
              icon={<EditOutlined />}
              onClick={() => setmodify({ content: record, visible: true })}
            >
              编辑
            </Tag>
            <Popconfirm
              title="确定要删除？"
              onConfirm={async (e) => {
                //TODO 后需要进行删除操作
                await deleteSchool.run({ collegeID: record.collegeID });
              }}
            >
              <Tag
                className="tags-hover delete"
                color="#f50"
                icon={<DeleteOutlined />}
              >
                删除
              </Tag>
            </Popconfirm>
          </small>
        );
      },
    },
  ];

  const [columnsKey, setcolumnsKey] = useState<any[]>([]);

  const [realColumns, setrealColumns] = useState<any[]>([]);

  const [addVisible, setaddVisible] = useState(false);

  const [requestParams, setrequestParams] = useState<RequestParams>({
    collegeName: "",
    contact: "",
    contactPhone: "",
    begin: 0,
    len: 10,
  });

  //点击刷新按钮
  function onRefresh() {
    getSchoolTable.run(requestParams);
  }

  //点击新增按钮
  function onAdd() {
    // setaddVisible({ visible: true, deptID: undefined })
    setaddVisible(true);
  }

  //监听变化

  useEffect(() => {
    const realColumns = columns.filter(
      (item) => columnsKey.indexOf(item.key) !== -1
    );
    setrealColumns(realColumns);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [columnsKey]);

  //当列改变的时候
  function onColumnsChange(checkedList: any[]) {
    // console.log(checkedList)
    setcolumnsKey(checkedList);
  }

  const [form] = Form.useForm();

  //点击完成的时候
  function handleFinish(value: Store) {
    // console.log(value);
    const params = {
      collegeName:
        typeof value.collegeName === "undefined" ? "" : value.collegeName,
      contact: typeof value.contact === "undefined" ? "" : value.contact,
      contactPhone:
        typeof value.contactPhone === "undefined" ? "" : value.contactPhone,
      begin: 0,
      len: 10,
    };

    setrequestParams({ ...params });
  }

  //点击重置的时候
  function handleReset() {
    form.resetFields();
    const params = {
      collegeName: "",
      contact: "",
      contactPhone: "",
      begin: 0,
      len: 10,
    };
    setrequestParams(params);
  }

  const dispatch = useDispatch();

  //获取学校的table信息
  async function getSchoolTableRequest(params: RequestParams) {
    try {
      const json = await fetchRequest(url.GET_SCHOOL_TABLE, params);
      if (json.success) {
        dispatch({
          type: schoolType.GET_SCHOOL_TABLE,
          payload: { data: json.data, count: json.count },
        });
      } else {
        message.destroy();
        message.error(json.error);
      }
    } catch (error: any) {
      message.destroy();
      message.error(error.message);
    }
  }

  const getSchoolTable = useRequest(getSchoolTableRequest, {
    loadingDelay: 200,
    manual: true,
  });

  const tableData = useSelector((state: any) => {
    // console.log(state)
    // return state.schoolManage.tableData
    return state.schoolManage.tableData;
  });

  useEffect(() => {
    getSchoolTable.run(requestParams);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [requestParams]);

  const { data, run } = useRequest(
    () => fetchRequest(url.COLLEGE_LIST_EXPORT, {}),
    {
      manual: true,
      onSuccess(data) {
        console.log(data.data);

        const temp = {
          collegeName: "学校名称",
          addrDesc: " 地址",
          contact: "联系人",
          contactPhone: " 联系电话",
          collegeTerm: "学段",
          area: "所属教育局",
          regionName: "行政区域",
          createDate: "创建时间",
        };

        const list = data.data.map((item: any) => {
          return {
            学校名称: item?.collegeName,
            地址: item?.addrDesc,
            联系人: item?.contact,
            联系电话: item?.contactPhone,
            学段: item?.collegeTerm,
            所属教育局: item?.area,
            行政区域: item?.regionName,
            创建时间: item?.createDate,
          };
        });

        exportExcel(list, "学校管理导出.xlsx");
      },
    }
  );

  /*批量导出*/
  const download = async () => {
    await run();
  };
  //查询框
  const searchForm = (
    <Card className="search-form">
      <Form
        form={form}
        layout="inline"
        onFinish={handleFinish}
        onReset={handleReset}
      >
        <Form.Item
          className="form-control-item"
          name="collegeName"
          label="学校名称"
        >
          <Input className="search-form-item" />
        </Form.Item>
        <Form.Item
          className="form-control-item"
          name="contact"
          label="管理人姓名"
        >
          <Input className="search-form-item" />
        </Form.Item>
        <Form.Item
          className="form-control-item"
          name="contactPhone"
          label="管理人电话"
        >
          <Input className="search-form-item" />
        </Form.Item>
        <Form.Item className="form-control-item">
          <Button
            key="1"
            type="primary"
            icon={<SearchOutlined />}
            htmlType="submit"
            style={{ marginRight: "8px" }}
          >
            搜索
          </Button>
          <Button key="2" icon={<SyncOutlined />} htmlType="reset">
            重置
          </Button>
          <Button
            type="primary"
            icon={<DownloadOutlined />}
            style={{ marginLeft: "8px" }}
            onClick={download}
          >
            批量导出
          </Button>
        </Form.Item>
      </Form>
    </Card>
  );

  //新增成功的调用
  function addSuccess() {
    message.destroy();
    message.success("新增成功!");
    setaddVisible(false);
    getSchoolTable.run(requestParams);
  }

  //修改成功时候的调用
  function modifySuccess() {
    message.destroy();
    message.success("修改成功!");
    setmodify({ ...modify, visible: false });
    getSchoolTable.run(requestParams);
  }

  //点击分页的时候
  function handlePageChange(page: number) {
    setrequestParams({ ...requestParams, begin: (page - 1) * 10 });
  }

  //点击删除时候的请求
  async function deleteSchoolRequest(params: DeleteParams) {
    try {
      const json = await fetchRequest(url.DELETE_SCHOOL_URL, params);
      if (json.success) {
        if (
          tableData.count > 10 &&
          tableData.count - 1 === requestParams.begin
        ) {
          setrequestParams({
            ...requestParams,
            begin: requestParams.begin - 10,
          });
        } else {
          getSchoolTable.run(requestParams);
        }

        message.success(json.msg);
      } else {
        message.destroy();
        message.error(json.msg);
      }
    } catch (error: any) {
      message.destroy();
      message.error(error.message);
    }
  }

  const deleteSchool = useRequest(deleteSchoolRequest, {
    manual: true,
  });

  return (
    <div>
      {searchForm}

      <Card className="search-form-table">
        <TableToolbar
          tableName="学校管理表"
          columns={columns}
          onColumnsChange={onColumnsChange}
          onRefresh={onRefresh}
          onAdd={onAdd}
        />
        <Table
          rowKey={(record: any) => record.collegeID}
          loading={getSchoolTable.loading}
          pagination={{
            hideOnSinglePage: true,
            simple: true,
            current: requestParams.begin / 10 + 1,
            onChange: handlePageChange,
            total: tableData.count,
            showSizeChanger: false,
          }}
          columns={realColumns}
          dataSource={tableData.data}
        />
        <Drawer
          destroyOnClose
          title="新增学校"
          width="40%"
          visible={addVisible}
          onClose={() => setaddVisible(false)}
        >
          <AddSchool addSuccess={addSuccess} />
        </Drawer>

        <Drawer
          destroyOnClose
          title="修改学校信息"
          width="40%"
          visible={modify.visible}
          onClose={() => setmodify({ ...modify, visible: false })}
        >
          <ModifySchool
            content={modify.content}
            modifySuccess={modifySuccess}
          />
        </Drawer>
      </Card>
    </div>
  );
}
